<script setup>

import {Notebook, Select} from "@element-plus/icons-vue";
import Card from "@/components/Card.vue";
import {computed, onMounted, reactive, ref} from "vue";
import {useStore} from "@/store/store.js";
import {post, get, accessHeader} from "@/net";
import {ElMessage} from "element-plus";
import axios from "axios";

const store = useStore()
const description = ref('')
const registerTime = computed(() => store.user.registerTime.toLocaleString())
const loading = reactive({
  form: true,
  save: false,
})
const detailsForm = reactive({
  username: '',
  sex: '0',
  phone: '',
  qq: '',
  wx: '',
  description: '',
  email: ''
})
const detailsFormRef = ref(null)

const validateUsername = (rule, value, callback) => {
  if (value === '') {
    callback(new Error("请输入用户名"))
  } else if (!/^[a-zA-Z0-9\u4e00-\u9fa5]+$/.test(value)) {
    callback(new Error("用户名不能包含特殊字符，只能是中文/英文"))
  } else {
    callback()
  }
}

const detailsFormRule = {
  username: [
    {validator: validateUsername, trigger: ['blur', 'change']},
    {min: 2, max: 10, message: '用户名长度需要在2~10个字符', trigger: ['blur', 'change']}
  ],
  email: [
    {required: true, message: '请输入邮件地址', trigger: 'blur'},
    {type: 'email', message: '请输入合法的电子邮件地址', trigger: ['blur', 'change']}
  ]
}

const getDetails = () => {
  get('api/user/details', response => {
    const data = response.data
    // console.log(data)
    // console.log(store)
    detailsForm.username = store.user.username
    detailsForm.email = store.user.email
    detailsForm.sex = data.sex
    detailsForm.phone = data.phone
    detailsForm.qq = data.qq
    detailsForm.wx = data.wx
    detailsForm.description = description.value = data.description
    loading.form = false
    console.log(detailsForm)
  })
}
const saveDetails = () => {
    detailsFormRef.value.validate(valid => {
      if (!valid) return
      loading.save = true
      post('api/user/saveDetails', detailsForm, () => {
        ElMessage.success('保存成功')
        store.user.username = detailsForm.username
        store.user.email = detailsForm.email
        description.value = detailsForm.description
        loading.save = false
      },() =>{
        ElMessage.error('保存失败')
        loading.save = false
      })
    })
}
const beforeUpload = (file) => {
  if (file.type != 'image/jpeg' && file.type != 'image/png') {
    ElMessage.warning('只能上传PNG/JPEG图片')
    return false
  } else if (file.size / 1024 > 1024) {
    ElMessage.warning('图片大小不能超过1M')
    return false
  } else {
    return true
  }
}

const uploadSuccess = (res) => {
  ElMessage.success('头像上传成功')
  store.user.avatar = res.data
}
onMounted(() => {
  getDetails()
})
</script>

<template>
  <div style="display: flex;max-width:1200px;margin: auto;">
    <div class="settings-left">
      <card :icon="Notebook" title="账号信息设置"
            description="在这里编辑您的个人信息，您可以在隐私设置中选择是否展示这些信息">
        <el-form :model="detailsForm" label-position="top" :rules="detailsFormRule" ref="detailsFormRef"
                 style="margin:0 10px 20px 10px " >
          <el-form-item label="用户名" prop="username">
            <el-input v-model="detailsForm.username"></el-input>
          </el-form-item>
          <el-form-item label="性别" prop="sex">
            <el-radio-group v-model="detailsForm.sex">
              <el-radio :value="0">男</el-radio>
              <el-radio :value="1">女</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="手机号" prop="phone">
            <el-input v-model="detailsForm.phone" maxlength="11" type="text"></el-input>
          </el-form-item>
          <el-form-item label="QQ" prop="qq">
            <el-input v-model="detailsForm.qq" maxlength="12" type="text"></el-input>
          </el-form-item>
          <el-form-item label="微信" prop="wx">
            <el-input v-model="detailsForm.wx" maxlength="20"></el-input>
          </el-form-item>
          <el-form-item label="个人简介" prop="description">
            <el-input v-model="detailsForm.description" type="textarea" :rows="6" maxlength="200"></el-input>
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="detailsForm.email"></el-input>
          </el-form-item>
          <el-button type="success" @click="saveDetails()" :loading="loading.save">
            <el-icon style="margin-right: 3px"><Select/></el-icon>
            保存用户信息
          </el-button>
        </el-form>
      </card>
    </div>

    <div class="settings-right">
      <div style="position: sticky;top: 20px">
        <card>
          <div style="text-align: center;padding: 5px 15px 0 15px;">
            <el-avatar size="default" :src="store.getAvatarURL" />
            <div style="margin: 5px 0">
              <el-upload :action="axios.defaults.baseURL + '/api/image/uploadImage'"
                         :show-file-list="false"
                         :before-upload="beforeUpload"
                         :on-success="uploadSuccess"
                         :headers="accessHeader()">
                <el-button size="small" round >上传头像</el-button>
              </el-upload>
            </div>
            <div style="font-weight: bold">
              您好, {{ store.user.username }}
            </div>
            <el-divider style="margin: 10px 0"/>
            <div style="font-size: 14px;color: gray;padding: 10px">
              {{ description || '这个用户很懒，没有填写个人简介！'}}
            </div>
          </div>
        </card>
        <card style="margin-top: 10px;font-size: 14px">
          <div>账号注册时间：{{ registerTime }}</div>
          <div style="color: gray">欢迎加入我们的开放论坛！</div>
        </card>
      </div>
    </div>
  </div>
</template>

<style scoped>

.settings-left {
  flex: 1;
  margin: 20px;
}

.settings-right {
  width: 300px;
  margin: 20px 30px 20px 0;
}

</style>